const util = require('util')
const axios = require('axios')
const {User} = require('../models/user')
const WXBizDataCrypt = require('../../core/WXBizDataCrypt')
const {generateToken} = require('../../core/util')
const {Auth} = require('../../middlewares/auth')

class WXManager {
  static async codeToToken (type, code, iv, encryptedData) {
    //微信服务传参形式 监听小程序用户是否合法 需要3个参数 code appid appsecret
    const url = util.format(global.config.wx.loginUrl, global.config.wx.appId, global.config.wx.appSecret, code)
    const res = await axios.get(url)
    if(res.status !== 200) {
      throw new global.errs.AuthFailed('openid获取失败')
    }
    if(res.data.errcode) {
      console.log(res.data)
      throw new global.errs.AuthFailed('openid获取失败:' + res.data.errmsg)
    }
    
    //获取unionid
    if(type === 'unionid') {
      const session_key = res.data.session_key
      encryptedData = encryptedData.replace(/ /g,'+')
      iv = iv.replace(/ /g,'+');
      const pc = new WXBizDataCrypt(global.config.wx.appId, session_key)
      try {
        var data = pc.decryptData(encryptedData , iv)
      } catch (error) {
        throw new global.errs.AuthFailed('解密失败，wx.login必须在wx.getUserInfo之前')
      }
      // console.log('解密后 data: ', data)
      if(data.openId) {
        var user = await User.getUserByWxId('openid', data.openId)
        if(!user) {
          user = await User.registerByWxId('openid', data.openId)
        }
      }else{
        throw new global.errs.AuthFailed('解密后unionId没有值')
      }
    }
    // 解密后的数据为
    //
    // data = {
    //   "nickName": "Band",
    //   "gender": 1,
    //   "language": "zh_CN",
    //   "city": "Guangzhou",
    //   "province": "Guangdong",
    //   "country": "CN",
    //   "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
    //   "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
    //   "watermark": {
    //     "timestamp": 1477314187,
    //     "appid": "wx4f4bc4dec97d474b"
    //   }
    // }

    // 获取openid
    else{
      let user = await User.getUserByWxId('openid', res.data.openid)
      if(!user) {
        user = await User.registerByWxId('openid', res.data)
      }
    }
    return generateToken(user.id, Auth.USER)
  }
}

module.exports = {
  WXManager
}